import { Button } from "antd";
import { ChangeEvent, FC, ReactElement, useRef, useState } from "react";
import styled from "styled-components";
import { checkUsernameValid } from "../../../api/authApi";
import { useAuth } from "../../../api/AuthContext";
import RASEncrypt from "../../../utils/JSEncrypt";
import { flexCenter } from "../../BUI/styled";
import { AnimateInput } from "../../MD/TitleInput";

interface IProps {}

const UpdateUsername: FC<IProps> = (): ReactElement => {
  const { updateUsername } = useAuth();
  const [showConfirmInput, setShowConfirmInput] = useState(false);
  const [loading, setLoading] = useState(false);
  const [usernameValid, setUsernameValid] = useState(true);
  const timer = useRef<any>(0);
  const username = useRef<HTMLInputElement>(null);
  const password = useRef<HTMLInputElement>(null);

  const checkUsername = (e: ChangeEvent<HTMLInputElement>) => {
    clearTimeout(timer.current);
    timer.current = setTimeout(() => {
      e.target.value &&
        checkUsernameValid(e.target.value).then(res => {
          setUsernameValid(res);
        });
    }, 500);
  };

  const requestUpdateUsername = async () => {
    if (!password.current || !username.current) return;
    //服务端 old username 从 jwt 中获得
    const params = {
      password: RASEncrypt(password.current.value),
      newUsername: username.current.value,
    };
    console.log(params);
    setLoading(true);
    await updateUsername(params);
    setLoading(false);
    setShowConfirmInput(false);
  };

  return (
    <Wrap>
      <input
        ref={username}
        onChange={checkUsername}
        type='text'
        placeholder='新的用户名'
      />
      <Button
        type='primary'
        onClick={() => {
          username.current &&
            username.current.value &&
            usernameValid &&
            setShowConfirmInput(true);
        }}
        danger={!usernameValid}
      >
        {!usernameValid ? "该用户名已被注册" : "确定"}
      </Button>
      <Mask show={showConfirmInput}>
        <input ref={password} type='password' placeholder='输入密码以确定' />
        <div>
          <Button
            type='ghost'
            onClick={() => {
              setShowConfirmInput(false);
            }}
          >
            取消
          </Button>

          <Button
            type='primary'
            onClick={requestUpdateUsername}
            loading={loading}
          >
            确定
          </Button>
        </div>
      </Mask>
    </Wrap>
  );
};

export default UpdateUsername;

export const Mask = styled.div<{ show?: boolean }>`
  position: absolute;
  background: #999;
  left: 0;
  width: 100%;
  height: 100%;
  ${flexCenter};
  flex-direction: column;
  opacity: ${props => (props.show ? 1 : 0)};
  top: ${props => (props.show ? 0 : "-100px")};
  z-index: ${props => (props.show ? 1 : -1)};
  transition-duration: 0.3s;
  transition-property: opacity, top, z-index;
  transition-delay: 0, 0, 0.3s;
  transition-timing-function: ease-in-out;

  * > button {
    margin: 5px;
  }
`;

export const Wrap = styled.div`
  flex-direction: column;
  ${flexCenter};

  input {
    ${AnimateInput};
    height: 50px;
    width: 300px;
    padding-left: 10px;
    flex: none;
    font-size: 18px;
    background-color: #ccc;
    margin-bottom: 10px;
  }
`;
